import pymem
from pymem.exception import MemoryReadError, WinAPIError


def readPointer(ModuleName, offsets):
    def get_module_addr(ModuleName):
        modules = list(process.list_modules())
        for module in modules:
            if module.name == ModuleName:
                return module.lpBaseOfDll
        return None
    base_module = get_module_addr(ModuleName)
    if base_module is not None:
        try:
            current_address = base_module
            for i, offset in enumerate(offsets):
                if i < len(offsets) - 1:
                    current_address = process.read_int(current_address + offset)                    
                else:
                    if current_address == 0:
                        #print('当前地址为零')
                        return None
                    current_address += offset
                if current_address == 0:
                 #print('当前地址为零')
                 return None
            return current_address
        except MemoryReadError as e:
            #print(f'无法读取内存: {e}')
            return None
        except WinAPIError as e:
            #print(f'Windows API错误: {e}')
            return None
    else:
        #print('找不到模块基址')
        return None

def ConnectProcess(ProcessName):
    while True:
        try:
            process = pymem.Pymem(ProcessName)
            # 如果成功连接到进程，执行Playvoice
            print(f"已找到 {ProcessName}")
            return process  # 返回连接到的进程对象
        except pymem.exception.ProcessNotFound:
            # 如果进程未找到，等待5秒后再次尝试
            print("进程未找到，5秒后重试...")
            time.sleep(5)

ProcessName = "MBAA.exe"
ModuleName = "MBAA.exe"
P1Pointer = [0xBA530, 0x6]
P2Pointer = [0xBA530, 0xC]
process = ConnectProcess(ProcessName)

p = int(input("请输入P: "))
v = int(input("请输入动作: "))
if p == 1:
     process.write_int(readPointer(ModuleName, P1Pointer), v)
else:
     process.write_int(readPointer(ModuleName, P2Pointer), v)
process.close_process()